package com.zzu.view.fragment;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.zzu.MyApplication;
import com.zzu.R;
import com.zzu.databinding.FragmentTransportInfoBindingImpl;
import com.zzu.model.bean.PackageRoute;
import com.zzu.utils.AppStorage;
import com.zzu.viewmodel.TransportViewModel;

import java.util.TimerTask;


public class TransportInfoFragment extends Fragment implements AMapLocationListener {

    private static final String TAG = TransportInfoFragment.class.getName();

    public static final String PACKAGE_ID = "package_id";
    public static final String PACKAGE_STATUS = "package_status";

    TransportViewModel mTransportViewModel;
    FragmentTransportInfoBindingImpl binding;

    java.util.Timer timer = null;
    //用于定位
    public AMapLocationClient mlocationClient;
    public AMapLocationClientOption mLocationOption = null;

    private Context mContext;
    private String packageId;
    private int status = 3;//状态默认是3
    public TransportInfoFragment() {
        // Required empty public constructor
    }

    public static TransportInfoFragment newInstance(String packageId,String status) {
        TransportInfoFragment fragment = new TransportInfoFragment();
        Bundle args = new Bundle();
        args.putString(PACKAGE_ID, packageId);
        args.putString(PACKAGE_STATUS, status);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            //获取包裹id
            packageId = getArguments().getString(PACKAGE_ID);
            status = Integer.parseInt(getArguments().getString(PACKAGE_STATUS));
            Log.i(TAG,"获得的包裹状态"+packageId+","+status);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding= DataBindingUtil.inflate(inflater, R.layout.fragment_transport_info,container,false);
        binding.tvExpressTransport.setText(packageId+"快递运输中");
        //获取ViewModel对象
        mTransportViewModel = new ViewModelProvider(this).get(TransportViewModel.class);
        binding.setData(mTransportViewModel);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //结束运输
                timer.cancel();
                binding.textView4.setText("暂无位置信息");
//                getActivity().finish();
            }
        });
        saveRoute();
    }

    private void saveRoute() {
        timer = new java.util.Timer(true);

        TimerTask task = new TimerTask() {
            public void run() {
                //进行定位
                Log.i(TAG,"执行一次定时任务");
                showLocation();
            }
        };

        //delay为long,period为long：从现在起过delay毫秒以后，每隔period毫秒执行一次。
        timer.schedule(task, 0, Long.parseLong(getResources().getString(R.string.transport_interval)));
    }

    private void showLocation() {
        try {
            mlocationClient = new AMapLocationClient(MyApplication.getContext());
            mLocationOption = new AMapLocationClientOption();
            mlocationClient.setLocationListener(this);
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            mLocationOption.setInterval(2000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            //启动定位
//            mlocationClient.startLocation(true);
//            mLocationOption.setOnceLocation(true);
//            mLocationOption.setNeedAddress(true);
            //启动定位
            mlocationClient.startLocation();
            Log.i(TAG,"启动定位");
        } catch (Exception e) {

        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        Log.i(TAG,"定位回调方法");
        try {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    //获取当前定位结果来源，如网络定位结果，详见定位类型表
                    Log.i("获取纬度", amapLocation.getLatitude() + "");
                    Log.i("获取经度", amapLocation.getLongitude() + "");

                    //如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    Log.i("地址", amapLocation.getAddress());
                    Log.i("国家信息", amapLocation.getCountry());
                    Log.i("省信息", amapLocation.getProvince());
                    Log.i("城市信息", amapLocation.getCity());
                    Log.i("城区信息", amapLocation.getDistrict());
                    Log.i("街道信息", amapLocation.getStreet());
                    Log.i("街道门牌号信息", amapLocation.getStreetNum());
                    Log.i("城市编码", amapLocation.getCityCode());
                    Log.i("地区编码", amapLocation.getAdCode());
                    PackageRoute packageRoute = new PackageRoute(packageId, amapLocation.getAdCode(), Long.parseLong(AppStorage.getUser().getId()),
                            status, amapLocation.getLatitude(), amapLocation.getLongitude(), amapLocation.getAddress());
                    // 停止定位
                    mlocationClient.stopLocation();
                    mTransportViewModel.saveRoute(mContext,packageRoute);
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG,"停止执行onpause");

    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG,"停止执行onstop");
        timer.cancel();
        if (null != mlocationClient) {
            mlocationClient.stopLocation();
        }
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != mlocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mlocationClient.onDestroy();
            mlocationClient = null;
        }
    }

    @Override
    public void onDestroy() {
        destroyLocation();
        super.onDestroy();
        timer.cancel();
        if (null != mlocationClient) {
            mlocationClient.stopLocation();
        }
    }
}